<?php
declare (strict_types = 1);

namespace app\admin\middleware;

use think\facade\Cache;
use think\facade\Session;

class CheckLogin
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        // 判断用户是否登录 前置中间件
        if (Session::has('managerInfo')) {
            # 已经登录
            #  统一拦截并进行权限检测
            # 当前登录用户的权限有那些？
            $auth_key = 'managerAuth'.Session::get("managerInfo.id");
            $auth = Cache::get($auth_key);
            $current_auth = [];
            foreach ($auth as $item) {
                foreach ($item['children'] as $value) {
                    $current_auth[] = $value['auth_c'].'/'.$value['auth_a'];
                }
            }
            # 当前访问的权限有哪些？
            $controller = $request->controller();
            $action = $request->action();
            $request_auth = $controller.'/'.$action;

           if (!in_array($request_auth,$current_auth)) {
               dd("你当前无权限操作");
           }

            return  $next($request);
        } else {
            # 未登录、跳转到登录页面
            return  redirect('/admin/login');
        }
    }
}
